// LoginController.java
package com.controller;

import com.entity.Users;
import com.mapper.UsersMapper;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class LoginController {

    @Autowired
    private UsersMapper usersMapper;

    @GetMapping("/login")//展示页面，用GetMapping
    public String loginPage() {
        //返回登录页面，登录页面在templates下的client文件夹下的login.html
        return "/client/login";
    }

    //提交登录
    @PostMapping("/toLogin")//表单提交，用PostMapping
    public String toLogin(Users users, HttpSession session) {
        //条件构造
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(Users::getUsername, users.getUsername());
        queryWrapper.eq(Users::getPassword, users.getPassword());
        //查询
        Users user = usersMapper.selectOneByQuery(queryWrapper);
        if (user != null) {//用户存在
            //登录成功，将用户信息保存到session中
            session.setAttribute("user", user);
            return "redirect:/";//重定向到首页
        } else {
            //登录失败
            return "/client/login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }
}
